package org.jeecg.modules.pos.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.modules.pos.entity.PosSellClearGoods;
import org.jeecg.modules.pos.entity.PosThali;
import org.jeecg.modules.pos.service.IPosSellClearGoodsService;
import org.jeecg.modules.pos.service.IPosThaliInGoodsService;
import org.jeecg.modules.pos.service.IPosThaliService;
import org.jeecg.modules.pos.service.impl.PosThaliInGoodsServiceImpl;
import org.jeecg.modules.rooms.Vo.CesGoodsVo;
import org.jeecg.modules.rooms.entity.CesGoods;
import org.jeecg.modules.rooms.entity.CesStockType;
import org.jeecg.modules.rooms.service.CesGoodsServiceImpl;
import org.jeecg.modules.rooms.service.CesStockTypeServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

 /**
 * @Description: pos_sell_clear_goods
 * @Author: jeecg-boot
 * @Date:   2023-04-11
 * @Version: V1.0
 */
@Api(tags="pos_sell_clear_goods")
@RestController
@RequestMapping("/pos/posSellClearGoods")
@Slf4j
public class PosSellClearGoodsController extends JeecgController<PosSellClearGoods, IPosSellClearGoodsService> {
	@Autowired
	private IPosSellClearGoodsService posSellClearGoodsService;
	@Autowired
	private CesGoodsServiceImpl cesGoodsService;
	@Autowired
	private CesStockTypeServiceImpl cesStockTypeService;
	@Resource
	private IPosThaliService posThaliService;
	@Resource
	private IPosThaliInGoodsService posThaliInGoodsService;

	 /**
	  * 商品沽清列表
	  * @param cesGoods
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @ApiOperation(value="pos_sell_clear_goods-分页列表查询", notes="pos_sell_clear_goods-分页列表查询")
	 @GetMapping(value = "/list2")
	 public Result<IPage<CesGoods>> queryPageList2(CesGoods cesGoods,
												  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
												  @RequestParam(name="goodTypes[]",required = false) List<String> goodTypes,
												  HttpServletRequest req) {
		 LambdaQueryWrapper<CesGoods> queryWrapper = QueryGenerator.initQueryWrapper(cesGoods, req.getParameterMap()).lambda();
		 queryWrapper.eq(CesGoods::getInvalid, false);
		 queryWrapper.eq(CesGoods::getIsTemp, false);
		 if (ObjectUtils.isNotEmpty(goodTypes)) {
			 List<CesStockType> list = cesStockTypeService.list(Wrappers.<CesStockType>lambdaQuery()
					 .eq(CesStockType::getHotelId, cesGoods.getHotelId())
					 .eq(CesStockType::getInvalid, false));
			 queryWrapper.and(j -> {
				 for (int k = 0; k < goodTypes.size(); k++) {
					 String id = goodTypes.get(k);
					 List<CesStockType> stockTypeList = list.stream().filter(t -> t.getParentId().equals(id)).collect(Collectors.toList());
					 if (ObjectUtils.isNotEmpty(stockTypeList)) {
						 for (int z = 0; z < stockTypeList.size(); z++) {
							 j = j.or().eq(CesGoods::getGoodType, stockTypeList.get(z).getId());
						 }
					 }
					 j = j.or().eq(CesGoods::getGoodType, id);
				 }
			 });
		 }
		 Page<CesGoods> page = new Page<CesGoods>(pageNo, pageSize);
		 IPage<CesGoods> pageList = cesGoodsService.page(page, queryWrapper);
		 pageList.getRecords().forEach(item -> {
			 LambdaQueryWrapper<PosSellClearGoods> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			 lambdaQueryWrapper.eq(PosSellClearGoods::getGoodsId, item.getId());
			 Long count = posSellClearGoodsService.count(lambdaQueryWrapper);
			 item.setIsSellClear(count > 0);
		 });
		 return Result.OK(pageList);
	 }

	 /**
	  * 商品沽清列表
	  * @param cesGoods
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @ApiOperation(value="pos_sell_clear_goods-分页列表查询", notes="pos_sell_clear_goods-分页列表查询")
	 @GetMapping(value = "/list")
	 public Result<IPage<CesGoods>> queryPageList(CesGoods cesGoods,
														   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
														   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
												  			@RequestParam(name="goodTypes[]",required = false) List<String> goodTypes,
												  			@RequestParam(name="keyw",required = false) String keyw,
														   HttpServletRequest req) {
		 LambdaQueryWrapper<CesGoods> queryWrapper = QueryGenerator.initQueryWrapper(cesGoods, req.getParameterMap()).lambda();
		 queryWrapper.eq(CesGoods::getInvalid, false);
		 queryWrapper.eq(CesGoods::getIsTemp, false);
		 if (StrUtil.isNotEmpty(keyw)){
			 queryWrapper.and(e -> e.eq(CesGoods::getBarCode, keyw).or().
					 like(CesGoods::getName, keyw).or().like(CesGoods::getSimplySpell, keyw.toUpperCase()));
		 }
		 if (ObjectUtils.isNotEmpty(goodTypes)) {
			 List<CesStockType> list = cesStockTypeService.list(Wrappers.<CesStockType>lambdaQuery()
					 .eq(CesStockType::getHotelId, cesGoods.getHotelId())
					 .eq(CesStockType::getInvalid, false));
			 queryWrapper.and(j -> {
				 for (int k = 0; k < goodTypes.size(); k++) {
					 String id = goodTypes.get(k);
					 List<CesStockType> stockTypeList = list.stream().filter(t -> t.getParentId().equals(id)).collect(Collectors.toList());
					 if (ObjectUtils.isNotEmpty(stockTypeList)) {
						 for (int z = 0; z < stockTypeList.size(); z++) {
							 j = j.or().eq(CesGoods::getGoodType, stockTypeList.get(z).getId());
						 }
					 }
					 j = j.or().eq(CesGoods::getGoodType, id);
				 }
			 });
		 }
		 Page<CesGoods> page = new Page<>(pageNo, pageSize);
		 IPage<CesGoods> pageList = cesGoodsService.page(page, queryWrapper);
		 pageList.getRecords().forEach(item -> {
			 if (item.getInventory() <= 0) {
				 item.setIsSellClear(true);
			 } else {
				 LambdaQueryWrapper<PosSellClearGoods> lambdaQueryWrapper = new LambdaQueryWrapper<>();
				 lambdaQueryWrapper.eq(PosSellClearGoods::getGoodsId, item.getId());
				 Long count = posSellClearGoodsService.count(lambdaQueryWrapper);

				 item.setIsSellClear(count > 0);
			 }
		 });
		 return Result.OK(pageList);
	 }

	 /**
	  * 套餐列表
	  * @param posThali
	  * @param pageNo
	  * @param pageSize
	  * @param goodTypes
	  * @param req
	  * @return
	  */
	 @GetMapping(value = "/thali-list")
	 public Result<IPage<PosThali>> queryPageThaliList(PosThali posThali,
												  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
												  @RequestParam(name="goodTypes[]",required = false) List<String> goodTypes,
												  HttpServletRequest req) {
		 LambdaQueryWrapper<PosThali> queryWrapper = QueryGenerator.initQueryWrapper(posThali, req.getParameterMap()).lambda();
		 queryWrapper.eq(PosThali::getState, true);
		 if (ObjectUtils.isNotEmpty(goodTypes)) {
			 List<CesStockType> list = cesStockTypeService.list(Wrappers.<CesStockType>lambdaQuery()
					 .eq(CesStockType::getHotelId, posThali.getHotelId())
					 .eq(CesStockType::getInvalid, false));
			 queryWrapper.and(j -> {
				 for (int k = 0; k < goodTypes.size(); k++) {
					 String id = goodTypes.get(k);
					 List<CesStockType> stockTypeList = list.stream().filter(t -> t.getParentId().equals(id)).collect(Collectors.toList());
					 if (ObjectUtils.isNotEmpty(stockTypeList)) {
						 for (int z = 0; z < stockTypeList.size(); z++) {
							 j = j.or().eq(PosThali::getThailType, stockTypeList.get(z).getId());
						 }
					 }
					 j = j.or().eq(PosThali::getThailType, id);
				 }
			 });
		 }
		 Page<PosThali> page = new Page<PosThali>(pageNo, pageSize);
		 IPage<PosThali> pageList = posThaliService.page(page, queryWrapper);
		 List<String> thaliIds = pageList.getRecords().stream().map(PosThali::getId).collect(Collectors.toList());
		 pageList.getRecords().forEach(c -> {
			 List<CesGoodsVo> goodsVos = posThaliInGoodsService.getThaliInGoodsDetail(thaliIds);
			 c.setCesGoodsList(goodsVos);
		 });
		 return Result.OK(pageList);
	 }

	/**
	 *   添加
	 *
	 * @param posSellClearGoods
	 * @return
	 */
	@AutoLog(value = "pos_sell_clear_goods-添加")
	@ApiOperation(value="pos_sell_clear_goods-添加", notes="pos_sell_clear_goods-添加")
	//@RequiresPermissions("pos:pos_sell_clear_goods:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody List<PosSellClearGoods> posSellClearGoods) {
		posSellClearGoods.forEach(t -> {
			if (t.getTenantId() == null || t.getTenantId().equals("")) {
				LoginUser user = TokenUtils.getAuthUser();
				if (user.getRelTenantIds() != null && !user.getRelTenantIds().equals("")) {
					t.setTenantId(user.getRelTenantIds());
				} else {
					throw new JeecgBootException("当前登录人租户信息错误");
				}
			}
			LambdaQueryWrapper<PosSellClearGoods> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			lambdaQueryWrapper.eq(PosSellClearGoods::getGoodsId, t.getGoodsId());
			posSellClearGoodsService.remove(lambdaQueryWrapper);
			posSellClearGoodsService.save(t);

		});
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param posSellClearGoods
	 * @return
	 */
	@AutoLog(value = "pos_sell_clear_goods-编辑")
	@ApiOperation(value="pos_sell_clear_goods-编辑", notes="pos_sell_clear_goods-编辑")
	//@RequiresPermissions("pos:pos_sell_clear_goods:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody PosSellClearGoods posSellClearGoods) {
		posSellClearGoodsService.updateById(posSellClearGoods);
		return Result.OK("编辑成功!");
	}
	 /**
	  *   通过goodsId删除
	  *
	  * @param goodsId
	  * @return
	  */
	 @AutoLog(value = "pos_sell_clear_goods-通过id删除")
	 @ApiOperation(value="pos_sell_clear_goods-通过id删除", notes="pos_sell_clear_goods-通过id删除")
	 //@RequiresPermissions("pos:pos_sell_clear_goods:delete")
	 @DeleteMapping(value = "/delete")
	 public Result<String> delete(@RequestParam(name="goodsId",required=true) String goodsId) {
		 Arrays.asList(goodsId.split(",")).forEach(t -> {
			 LambdaQueryWrapper<PosSellClearGoods> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			 lambdaQueryWrapper.eq(PosSellClearGoods::getGoodsId, t);
			 posSellClearGoodsService.remove(lambdaQueryWrapper);
		 });
		 return Result.OK("删除成功!");
	 }

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "pos_sell_clear_goods-批量删除")
	@ApiOperation(value="pos_sell_clear_goods-批量删除", notes="pos_sell_clear_goods-批量删除")
	//@RequiresPermissions("pos:pos_sell_clear_goods:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.posSellClearGoodsService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "pos_sell_clear_goods-通过id查询")
	@ApiOperation(value="pos_sell_clear_goods-通过id查询", notes="pos_sell_clear_goods-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<PosSellClearGoods> queryById(@RequestParam(name="id",required=true) String id) {
		PosSellClearGoods posSellClearGoods = posSellClearGoodsService.getById(id);
		if(posSellClearGoods==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(posSellClearGoods);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param posSellClearGoods
    */
    //@RequiresPermissions("pos:pos_sell_clear_goods:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, PosSellClearGoods posSellClearGoods) {
        return super.exportXls(request, posSellClearGoods, PosSellClearGoods.class, "pos_sell_clear_goods");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("pos:pos_sell_clear_goods:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, PosSellClearGoods.class);
    }

}
